﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace ProjectX.Lib
{
    public class SystemLib
    {
        private static string _appKey;
        private static string _appSecret;

        /// <summary>
        /// 验证回调地址的签名是否合法。
        /// </summary>
        /// <param name="callbackUrl">回调地址</param>
        /// <param name="appSecret">应用密钥</param>
        /// <returns>验证成功返回True，否则返回False</returns>
        public static bool VerifyTopResponse(string callbackUrl, string appSecret)
        {
            Uri uri = new Uri(callbackUrl);

            string query = uri.Query;
            if (string.IsNullOrEmpty(query)) // 没有回调参数
            {
                return false;
            }

            query = query.Trim(new char[] { '?', ' ' });
            if (query.Length == 0) // 没有回调参数
            {
                return false;
            }

            IDictionary<string, string> queryDict = new Dictionary<string, string>();
            string[] queryParams = query.Split(new char[] { '&' });

            if (queryParams != null && queryParams.Length > 0)
            {
                foreach (string queryParam in queryParams)
                {
                    string[] oneParam = queryParam.Split(new char[] { '=' });
                    if (oneParam.Length >= 2)
                    {
                        queryDict.Add(oneParam[0], oneParam[1]);
                    }
                }
            }

            StringBuilder result = new StringBuilder();
            if (queryDict.ContainsKey("top_appkey")) result.Append(queryDict["top_appkey"]);
            if (queryDict.ContainsKey("top_parameters")) result.Append(queryDict["top_parameters"]);
            if (queryDict.ContainsKey("top_session")) result.Append(queryDict["top_session"]);
            result.Append(appSecret);

            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));
            string sign = System.Convert.ToBase64String(bytes);

            return queryDict.ContainsKey("top_sign") && Uri.EscapeDataString(sign) == queryDict["top_sign"];
        }

        /// <summary>
        /// 验证回调地址的签名是否合法。
        /// </summary>
        /// <param name="topParams">TOP私有参数（未经Base64解密后的）</param>
        /// <param name="topSession">TOP私有会话码</param>
        /// <param name="topSign">TOP回调签名（经过URL反编码的）</param>
        /// <param name="appKey">应用公钥</param>
        /// <param name="appSecret">应用密钥</param>
        /// <returns>验证成功返回True，否则返回False</returns>
        public static bool VerifyTopResponse(string topParams, string topSession, string topSign, string appKey, string appSecret)
        {
            StringBuilder result = new StringBuilder();

            //System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            result.Append(appKey).Append(topParams).Append(topSession).Append(appSecret);

            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));

            return System.Convert.ToBase64String(bytes) == topSign;
        }


        public static string Appkey
        {
            set { _appKey = value; }
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["AppKey"] != null)
                {
                    _appKey = System.Configuration.ConfigurationManager.AppSettings["AppKey"];
                    return _appKey;
                }
                else
                {
                    return "";
                }
            }
        }

        public static string AppSecret
        {
            set { _appSecret = value; }
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["AppSecret"] != null)
                {
                    _appSecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"];
                    return _appSecret;
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 解析回调地址中top_parameters中的值
        /// </summary>
        /// <param name="key">取值关键词</param>
        /// <returns></returns>
        public string GetParameters(string parameters, string key)
        {
            string ret = string.Empty;
            try
            {
                string str = Base64ToString(parameters);
                string[] param = str.Split('&');
                for (int i = 0; i < param.Length; i++)
                {
                    string[] info = param[i].Split('=');
                    if (info[0].ToLower() == key.ToLower())
                    {
                        ret = info[1];
                        break;
                    }
                }
            }
            catch (Exception exp)
            {
                //
            }
            return ret;
        }


        /// <summary>
        /// Base64 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Base64ToString(string str)
        {
            return System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(str));
        }


        private static bool _SandBox = false;
        /// <summary>
        /// 是否沙箱环境 (true=沙箱,false=正式环境,默认是正式环境)
        /// </summary>
        public static bool SendBox
        {
            set { _SandBox = value; }
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["SandBox"] != null)
                {
                    if (System.Configuration.ConfigurationManager.AppSettings["SandBox"].ToString() == "1")
                    {
                        _SandBox = true;
                    }
                    else
                    {
                        _SandBox = false;
                    }
                }
                return _SandBox;
            }
        }

        private static string _containerAuthCodeURL = SendBox ? "http://container.api.tbsandbox.com/container?authcode={0}" : "http://container.open.taobao.com/container?authcode={0}";
       
        /// <summary>
        /// 授权容器地址  正式环境：http://container.open.taobao.com/container?authcode={授权码}
        /// <para>测试环境：http://container.api.tbsandbox.com/container?authcode={0}</para>
        /// <para>旧测试环境：http://container.sandbox.taobao.com/container?authcode={0}</para>
        /// </summary>
        public static string ContainerAuthCodeURL
        {
            set { _containerAuthCodeURL = value; }
            get { return _containerAuthCodeURL; }
        }

        private static string _topUrl = SendBox ? "http://gw.api.tbsandbox.com/router/rest" : "http://gw.api.taobao.com/router/rest";

        public static string TopUrl
        {
            set { _topUrl = value; }
            get { return _topUrl; }
        }

        #region

        private SymmetricAlgorithm mobjCryptoService = new RijndaelManaged();
        ///   <summary> 
        ///   解密字符串密码;
        ///   </summary> 
        ///   <param   name= "Source "> 待解密的串 </param> 
        ///   <returns> 经过解密的串 </returns> 
        public string Decrypto(string Source)
        {
            byte[] bytIn = Convert.FromBase64String(Source);
            MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
            mobjCryptoService.Key = GetLegalKey();
            mobjCryptoService.IV = GetLegalIV();
            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);
            return sr.ReadToEnd();
        }


        ///   <summary> 
        ///   获得密钥 
        ///   </summary> 
        ///   <returns> 密钥 </returns> 
        private byte[] GetLegalKey()
        {
            string sTemp = "exsky001";
            mobjCryptoService.GenerateKey();
            byte[] bytTemp = mobjCryptoService.Key;
            int KeyLength = bytTemp.Length;
            if (sTemp.Length > KeyLength)
            {
                sTemp = sTemp.Substring(0, KeyLength);
            }
            else if (sTemp.Length < KeyLength)
            {
                sTemp = sTemp.PadRight(KeyLength, ' ');
            }
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
        ///   <summary> 
        ///   获得初始向量IV 
        ///   </summary> 
        ///   <returns> 初试向量IV </returns> 
        private byte[] GetLegalIV()
        {
            string sTemp = "hujk619";
            mobjCryptoService.GenerateIV();
            byte[] bytTemp = mobjCryptoService.IV;
            int IVLength = bytTemp.Length;
            if (sTemp.Length > IVLength)
            {
                sTemp = sTemp.Substring(0, IVLength);
            }
            else if (sTemp.Length < IVLength)
            {
                sTemp = sTemp.PadRight(IVLength, ' ');
            }
            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }
        #endregion
    }
}